
import { PageWarpperContext } from "@/src/components/page-warpper"
import { UserState } from "@/src/dva/models/user"
import { State } from "@/src/dva/state"
import Api from "@/src/lib/api/api"
import Global from "@/src/lib/global"
import { HomeCouponModel } from "@/src/lib/models/home_index_model"
import { Image, View, Text } from "@tarojs/components"
import { useContext } from "react"
import { connect } from "react-redux"
import HomeSection, { HomeSectionProps } from "./home-section"

import "./vip-coupon.scss"


interface VIPCouponProps extends HomeSectionProps {
    models: HomeCouponModel[],
    user: UserState
}


const VIPCouponItem = (props: {
    model: HomeCouponModel
    onClick: (model: HomeCouponModel) => void
}) => {

    return (
        <View className="vip-coupon-item" onClick={ () => props.onClick(props.model)}>
            <View className="desc">{ props.model.tip }</View>
            <View><Text className="symbol">￥</Text><Text className="price">{ Number.parseInt(props.model.price).toFixed(0) }</Text></View>
        </View>
    )
}

const VIPCoupon = (props: VIPCouponProps) => {

    let ctx = useContext(PageWarpperContext)
    let onItemClick = (model: HomeCouponModel) => {
        console.log(model)
        if (!props.user.isLogin) {
            ctx.loginCompentRef?.current?.show()
            return
        }

        Api.goodsCouponGet({
            id: model.id
        }).then( res => {
            console.log('res',res)
            if (!Api.handleResponse(res)) {
                return
            }
            Global.showToast("领取成功")
        })

    }

    let children = new Array()
    for (const model of props.models) {
        children.push(<VIPCouponItem  model={model} onClick={ onItemClick }/>)
    }

    return (
        <HomeSection {...props} backgroundImage="http://r.punkyangsheng.com/xcx/img/images/bg_home_section1@3x.png" className={[props.className, "vip-coupon"].join(" ")}>
            <View className="vip-coupon-title">会员优惠券</View>
            <View className="vip-coupon-content">
                <Image className="vip-coupon-content-bg" src={ Global.loadImage("bg_coupon@3x.png") } />
                <View className="vip-coupon-content-grid">
                    { children }
                </View>
            </View>
        </HomeSection>
    )
}

export default connect((state: State) => ({user: state.user}))(VIPCoupon)